#import "UIImage+YLMultiFormat.h"
#import "YLWebImageCodersManager.h"
#import "objc/runtime.h"

@implementation UIImage (YLMultiFormat)

- (NSUInteger)yl_imageLoopCount {
    NSUInteger imageLoopCount = 0;
    NSNumber *value = objc_getAssociatedObject(self, @selector(yl_imageLoopCount));
    if ([value isKindOfClass:[NSNumber class]]) {
        imageLoopCount = value.unsignedIntegerValue;
    }
    return imageLoopCount;
}

- (void)setYl_imageLoopCount:(NSUInteger)yl_imageLoopCount {
    NSNumber *value = @(yl_imageLoopCount);
    objc_setAssociatedObject(self, @selector(yl_imageLoopCount), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (YLImageFormat)yl_imageFormat {
    YLImageFormat imageFormat = YLImageFormatUndefined;
    NSNumber *value = objc_getAssociatedObject(self, @selector(yl_imageFormat));
    if ([value isKindOfClass:[NSNumber class]]) {
        imageFormat = value.integerValue;
        return imageFormat;
    }
    // Check CGImage's UTType, may return nil for non-Image/IO based image
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunguarded-availability"
    if (&CGImageGetUTType != NULL) {
        CFStringRef uttype = CGImageGetUTType(self.CGImage);
        imageFormat = [NSData yl_imageFormatFromUTType:uttype];
    }
#pragma clang diagnostic pop
    return imageFormat;
}

- (void)setYl_imageFormat:(YLImageFormat)yl_imageFormat {
    objc_setAssociatedObject(self, @selector(yl_imageFormat), @(yl_imageFormat), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

+ (nullable UIImage *)yl_imageWithData:(nullable NSData *)data {
    return [[YLWebImageCodersManager sharedInstance] decodedImageWithData:data];
}

- (nullable NSData *)yl_imageData {
    return [self yl_imageDataAsFormat:YLImageFormatUndefined];
}

- (nullable NSData *)yl_imageDataAsFormat:(YLImageFormat)imageFormat {
    NSData *imageData = nil;
    if (self) {
        imageData = [[YLWebImageCodersManager sharedInstance] encodedDataWithImage:self format:imageFormat];
    }
    return imageData;
}


@end
